package com.airlines.base.config.cglib;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

/**
 * @author xxxx
 * @date 2018年6月15日 
 * @description
 */
public class DynamicBean {

    /** 
      * 实体Object 
      */  
    private  Object target = null;  
  
    /** 
      * 属性map 
      */  
    private  BeanMap beanMap = null;  
  
    public DynamicBean() {  
        super();  
    }  
      
    @SuppressWarnings("rawtypes")
	public DynamicBean(Map propertyMap) {  
      this.target = generateBean(propertyMap);  
      this.beanMap = BeanMap.create(this.target);  
    }  
    
    @SuppressWarnings("rawtypes")
	public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
    	this.target = generateBean(superclass, propertyMap);
        this.beanMap = BeanMap.create(this.target);
    }
  
    /** 
      * 给bean属性赋值 
      * @param property 属性名 
      * @param value 值 
      */  
    public void setValue(String property, Object value) {  
      beanMap.put(property, value);  
    }  
  
    /** 
      * 通过属性名得到属性值 
      * @param property 属性名 
      * @return 值 
      */  
    public Object getValue(String property) {  
      return beanMap.get(property);  
    }  
  
    /** 
      * 得到该实体bean对象 
      * @return 
      */  
    public Object getTarget() {  
      return this.target;  
    }  
  
    /** 
     * @param propertyMap 
     * @return 
     */  
    @SuppressWarnings({ "rawtypes" })  
    private Object generateBean(Map propertyMap) {  
      BeanGenerator generator = new BeanGenerator();  
      Set keySet = propertyMap.keySet();  
      for (Iterator i = keySet.iterator(); i.hasNext();) {  
       String key = (String) i.next();  
       generator.addProperty(key, (Class) propertyMap.get(key));  
      }  
      return generator.create();  
    }  
    
    
    @SuppressWarnings({ "rawtypes" })
	private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
        BeanGenerator generator = new BeanGenerator();
        if (null != superclass) {
            generator.setSuperclass(superclass);
        }
        BeanGenerator.addProperties(generator, propertyMap);
        return generator.create();
    }
    

}
